// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  cloud.updateConfig({
    env: wxContext.ENV
  });

  const db = cloud.database();

  const { source_id, read_url, } = event;
  const source = await db
    .collection("book_sources")
    .doc(source_id)
    .field({ catalogs: true })
    .get();
  if (source.data && source.data.catalogs) {
    const catalogs = await cloud.callFunction({
      name: "worm",
      data: {
        url: read_url,
        type: source.data.catalogs.type,
        result: source.data.catalogs.result
      }
    });
    if (!catalogs.result || !catalogs.result.catalogs) {
      return { errMsg: "请求错误" };
    }
    return { errMsg: "ok", data: catalogs.result };
  } else {
    return { errMsg: "源错误" };
  }
};
